﻿using System.Xml.Serialization;
using System.IO;

namespace Halcyonetic.Common
{
    public class Xml
    {
        public class Deserialize
        {
            /// <summary>
            /// Deserialize a generic Xml file
            /// </summary>
            public static object Generic(string xml, object xmlType)
            {
                var objXml = new XmlSerializer(xmlType.GetType());
                var byteXml = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(xml);
                var memStreamXml = new MemoryStream(byteXml);
                var outPutObj = objXml.Deserialize(memStreamXml);
                memStreamXml.Dispose();
                memStreamXml.Dispose();
                return outPutObj;
            }

        }
        
        public class Serialize
        {

            /// <summary>
            /// Serialize a generic Xml file
            /// </summary>
            public static string Generic(object clXml, XmlSerializerNamespaces ns)
            {
                var objXml = new XmlSerializer(clXml.GetType());
                var memStreamXml = new MemoryStream();
                var streamReader = new StreamReader(memStreamXml);

                objXml.Serialize(memStreamXml, clXml, ns);
                memStreamXml.Seek(0, SeekOrigin.Begin);

                var strReturn = streamReader.ReadToEnd();
                memStreamXml.Dispose();
                streamReader.Dispose();
                return strReturn;
            }
        }
    }
}
